<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/polymer/lib/utils/settings.html">
<!-- import 3rd party elements -->
<link rel="import" href="../bower_components/polymerfire/polymerfire.html">
<link rel="import" href="../bower_components/vaadin-icons/vaadin-icons.html">
<!-- app elements - used for core functions -->
<link rel="import" href="../bower_components/app-storage/app-localstorage/app-localstorage-document.html">
<link rel="import" href="../bower_components/app-localize-behavior/app-localize-behavior.html">
<link rel="import" href="../bower_components/app-layout/app-layout.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-route/app-route.html">
<!-- iron elements used for component functions -->
<link rel="import" href="../bower_components/iron-selector/iron-selector.html">
<link rel="import" href="../bower_components/iron-pages/iron-pages.html">
<link rel="import" href="../bower_components/iron-icon/iron-icon.html">
<!-- import page router -->
<link rel="import" href="view-login.html">
<link rel="import" href="view-dashboard.html">
<link rel="import" href="view-setup.html">
<link rel="import" href="view-plan.html">
<link rel="import" href="view-track.html">
<link rel="import" href="view-help.html">
<link rel="import" href="view-settings.html">
<link rel="import" href="view-term.html">
<link rel="import" href="view-offline.html">
<link rel="import" href="view-error.html">
<link rel="import" href="view-404.html">
<link rel="import" href="lazy-resources.html">
<!-- import shared style component -->
<link rel="import" href="style/shared-styles.html">
<dom-module id="view-app">
  <template>
    <style include="shared-styles">
      :host {
        display: block;
      }
    </style>
    <app-location route="{{route}}" url-space-regex="^[[rootPath]]"></app-location>
    <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{pageData}}" tail="{{subRoute}}"></app-route>
    <app-route route="{{subRoute}}" pattern="/:page" data="{{routeData}}" tail="{{subPageRoute}}"></app-route>
    <firebase-app name="smart-mes" auth-domain="smart-mes.firebaseapp.com" database-url="https://smart-mes.firebaseio.com" api-key="AIzaSyAPkuFs7jRmku7qiNGUkLk0nmtQCy0s3M0"
      storage-bucket="smart-mes.appspot.com" messaging-sender-id="253401775445" project-id="smart-mes"></firebase-app>
    <firebase-auth app-name="smart-mes" id="userAuth" user="{{user}}" online="{{online}}" signed-in="{{signedIn}}" on-error="_handleError"></firebase-auth>
    <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{userData}}"></firebase-document>
    <firebase-document app-name="smart-mes" id="appLanguage" path="/data/[[userData.key]]/appData/language" data="[[language]]"></firebase-document>
    <app-localstorage-document id="appLang" key="app-lang" data="{{language}}"></app-localstorage-document>
    <iron-pages selected="[[pageData.page]]" attr-for-selected="name" fallback-selection="404" role="main">
      <view-term name="term" route="[[subRoute]]" hidden$="[[signedIn]]"></view-term>
      <view-login name="login" route="[[subRoute]]" hidden$="[[signedIn]]"></view-login>
      <view-404 name="404" route="[[subRoute]]"></view-404>
      <app-drawer-layout id="layout" fullbleed narrow="{{narrow}}" name="app">
       
        <app-drawer id="drawer" slot="drawer" tabindex="-1" swipe-open="[[narrow]]" hidden="[[!signedIn]]">
          <div style="height: 100%; overflow: auto;">
          <img class="app-logo" title="IMES" alt="Application logo" src="[[rootPath]]images/logo/logo.svg"/>
          <h1 title="IMES" class="main-logo-title">IMES</h1>
          <h2 title="Smart Industry Helper" class="main-describe">{{localize('app-description')}}</h2>
          <app-analytics key="UA-51514677-9"></app-analytics>
          <nav role="navigation">
            <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" fallback-selection="404" role="navigation">
              <a name="dashboard" role="link" href="[[rootPath]]app/dashboard" rel="dashboard" title="Dashboard">
                <paper-icon-button icon="vaadin:dashboard"></paper-icon-button> {{localize('view-index-menu-dashboard')}}</a>
              <a name="setup" role="link" href="[[rootPath]]app/setup" rel="setup" title="Setup">
                <paper-icon-button icon="vaadin:cogs"></paper-icon-button> {{localize('view-index-menu-setup')}}</a>
              <a name="plan" role="link" href="[[rootPath]]app/plan" rel="plan" title="Plan">
                <paper-icon-button icon="vaadin:calendar-clock"></paper-icon-button> {{localize('view-index-menu-plan')}}</a>
              <a name="track" role="link " href="[[rootPath]]app/track" rel="track" title="Track">
                <paper-icon-button icon="vaadin:progressbar"></paper-icon-button> {{localize('view-index-menu-track')}}</a>
              <a name="settings" role="link" href="[[rootPath]]app/settings" rel="settings" title="Settings">
                <paper-icon-button icon="vaadin:tools"></paper-icon-button> {{localize('settings')}}
              </a>
            </iron-selector>
          </nav>
          <div class="separator-line" role="separator"></div>
          <div class="flex-center">
            <paper-button class="logout-btn" on-click="logout" title="Logout">{{localize('logout-button')}}</paper-button>
            <div class="user-info">
              <img id="profile" alt="user image" class="profile-image" src="[[getUserImage(userData.photoURL)]]"/>
              <paper-tooltip position="bottom" for="profile" class="profile-tooltip">
                <p>[[userData.email]]</p>
                <p>{{localize('verify-status')}}:
                  <span class="verify">[[getVerifyStatus(user.emailVerified)]]</span>
                </p>
                <p>[[userData.company]]</p>
              </paper-tooltip>
              <p>[[userData.displayname]]</p>
              <p>{{localize('version')}} 1.1.5</p>
            </div>
          </div>
        </div>
        </app-drawer>

        <app-header-layout>
          <app-header class="main-header" id="header" slot="header" hidden="[[!signedIn]]">
            <app-toolbar>
              <paper-icon-button class="mobile-menu-btn" icon="icons:menu" drawer-toggle></paper-icon-button>
              <h2 class="page-title" main-title>[[getPageTitle(routeData.page)]]</h2>
            </app-toolbar>
          </app-header>
        </app-header-layout>
        <iron-pages selected="[[routeData.page]]" attr-for-selected="name" fallback-selection="404" selected-attribute="visible">
          <view-dashboard name="dashboard" route="[[subPageRoute]]" hidden$="[[!user]]"></view-dashboard>
          <view-setup name="setup" route="[[subPageRoute]]" hidden$="[[!user]]"></view-setup>
          <view-plan name="plan" route="[[subPageRoute]]" hidden$="[[!user]]"></view-plan>
          <view-track name="track" route="[[subPageRoute]]" hidden$="[[!user]]"></view-track>
          <view-settings name="settings" route="[[subPageRoute]]" hidden$="[[!user]]"></view-settings>
          <view-404 name="404" route="[[subPageRoute]]" hidden$="[[!user]]"></view-404>
          <view-offline name="offline" route="[[subPageRoute]]" hidden$="[[!user]]"></view-offline>
          <view-error name="error" route="[[subPageRoute]]" hidden$="[[!user]]"></view-error>
        </iron-pages>
      </app-drawer-layout>
    </iron-pages>
    <paper-toast id="toastVerify" class="toast-verify" always-on-top vertical-align="bottom" class="fit-bottom" duration="5000"
      hidden="true">
      <div class="toast-flex-container">
        <div class="toast-flex-item">
          <p>[[toastText]]</p>
        </div>
        <div class="toast-flex-item">
          <paper-icon-button on-click="closeToastAlert" class="close-toast-button" icon="vaadin:close-big" noink></paper-icon-button>
        </div>
      </div>
    </paper-toast>
  </template>
  <script>
    /**
     * #ViewApp
     * @ViewApp
     * @polymer
     */
    class ViewApp extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior], Polymer.Element) {
      static get is() {
        return 'view-app'
      }
      static get properties() {
        return {
          page: {
            type: String,
            reflectToAttribute: true,
            observer: '_pageChanged'
          },
          language: {
            type: String,
            value: () => {
              if (localStorage.getItem('app-lang')) {
                return localStorage.getItem('app-lang')
              } else if (localStorage.getItem('app-lang') == {} || !localStorage.getItem('app-lang')) {
                return 'us'
              } else {
                return language
              }
            }
          },
          user: {
            type: Object,
            notify: true
          },
          userData: {
            type: Object,
            notify: true
          },
          loadComplete: {
            type: Boolean,
            value: false
          },
          signedIn: Boolean,
          route: String,
          subRoute: String,
          subPageRoute: String,
          toastText: String,
          loading: Boolean,
          rootPath: String,
          online: Boolean
        }
      }
      static get observers() {
        return [
          '_routeChanged(subRoute.*)',
          '_routePageChanged(routeData.page)',
          '_verifyEmailAlert(user.emailVerified, signedIn)',
          '_signedInChanged(signedIn)'
        ]
      }
      constructor() {
        super()
        Polymer.setPassiveTouchGestures(true)
        Polymer.setRootPath(window.Polymer.rootPath)
      }
      connectedCallback() {
        super.connectedCallback()
        this.loadResources(this.resolveUrl('../data/locales.json'))
        requestAnimationFrame(this._installListeners.bind(this))
      }
      _installListeners() {
        Polymer.RenderStatus.afterNextRender(this, () => {
          this.addEventListener('show-invalid-url-warning', (e) => this._showPage404.bind(this))
          this.addEventListener('on-error', (e) => this.handleError(e))
          window.addEventListener('online', (e) => this._notifyNetworkStatus(e))
          window.addEventListener('offline', (e) => this._notifyNetworkStatus(e))
        })
      }
      logout() {
        if (this.online) {
          this.$.userAuth.signOut()
            .then(() => {
              Polymer.Async.timeOut.run(() => {
                this.closeToastAlert()
                this.page = 'login'
                this.set('route.path', '/login')
              }, 200)
            })
            .catch((error) => {
              this.page = 'error'
            })
        } else {
          this.page = 'offline'
        }
      }
      closeToastAlert() {
        this.$.toastVerify.close()
        this.$.toastVerify.hidden = true
      }
      getVerifyStatus(status) {
        if (status) {
          this.$$('.verify').style.color = 'green'
          return this.localize('verified')
        } else {
          this.$$('.verify').style.color = 'red'
          return this.localize('not-verify')
        }
      }
      getUserImage(url) {
        return ((url) ? url : 'images/profile/default.svg')
      }
      getPageTitle(title) {
        return this.localize(title)
      }
      _routeChanged(changeRecord) {
        //Close a non-persistent drawer when the page & route are changed.
        if (!this.$.drawer.persistent) {
          this.$.drawer.close()
        }
      }
      _routePageChanged(page) {
        if (!this.$.drawer.persistent) {
          this.$.drawer.close()
        }
        this.page = page || 'dashboard'
      }
      _showPage404() {
        this.page = '404'
      }
      _pageChanged(page, oldPage) {
        if (page == 'dashboard') {
          this._pageLoaded(Boolean(oldPage))
        } else {
          // Start loading the overview page after we're done showing the login page.
          requestAnimationFrame(() => {
            setTimeout(() =>
              Polymer.importHref(
                this.resolveUrl('view-' + page + '.html'),
                this._pageLoaded.bind(this, Boolean(oldPage)),
                this._showPage404.bind(this),
                true), 0);
          });
        }
      }
      _pageLoaded(shouldResetLayout) {
        this._ensureLazyLoaded()
        if (shouldResetLayout) {
          // The size of the header depends on the page (e.g. on some pages the tabs
          // do not appear), so reset the header's layout only when switching pages.
          Polymer.Async.timeOut.run(() => {
            this.$.drawer.resetLayout()
            this.$.layout.resetLayout()
          }, 1)
        }
      }
      _ensureLazyLoaded() {
        this.loadComplete || (this.loadComplete = true, Polymer.RenderStatus.afterNextRender(this, () => {
          Polymer.importHref(
            this.resolveUrl('lazy-resources.html'),
            () => {
              this.loadComplete = true
              this._notifyNetworkStatus()
            },
            this._showPage404.bind(this),
            true)
        }))
      }
      _signedInChanged(isSignedIn) {
          // If singed in but at login page
          if (isSignedIn && this.route.path === '/login') { 
            this.set('route.path', '/app/dashboard/overview')
          }
          // If not sign in but not at term page
          else if (!isSignedIn && this.route.path !== '/term') {
            this.set('route.path', '/login')
          }
      }
      _notifyNetworkStatus() {
        let oldOffline = this.offline
        this.offline = !navigator.onLine
        // Show the snackbar if the user is offline when starting a new session or if the network status changed.
        if (this.offline || (!this.offline && oldOffline === true)) {
          if (!this._networkSnackbar) {
            this._networkSnackbar = document.createElement('flat-toast')
            this.root.appendChild(this._networkSnackbar)
          }
          this._networkSnackbar.innerHTML = this.offline ? this.localize('notification-offline') : this.localize(
            'notification-online')
          this._networkSnackbar.setAttribute('duration', 5000)
          this.closeToastAlert()
          this._networkSnackbar.open()
          // Refresh network if internet go online
          if (!this.offline && oldOffline === true) {
            this._debouncer = Polymer.Debouncer.debounce(this._debouncer, Polymer.Async.timeOut.after(200), () => {
              this._refreshNetworkStatus()
            })
          }
        }
      }
      _refreshNetworkStatus() {
        this.$.userAuth.refreshNetworkStatus()
        this.$.userData.refreshNetworkStatus()
      }
      _verifyEmailAlert(verified, signedIn) {
        if (!verified && signedIn) {
          // Temporary Disable
          // this._showAlertToast(
          //   'we-could-not-verify-your-account'
          // )
        }
      }
      _showAlertToast(text) {
        this.toastText = this.localize(text)
        this.$.toastVerify.hidden = false
        this.$.toastVerify.open()
      }
      _handleError(e) {
        console.error('Error: ' + e.message)
        this.page = 'error'
      }
    }
    window.customElements.define(ViewApp.is, ViewApp)
  </script>
</dom-module>